<template>
    <div class="sales-order-list-container">
        <h2>销货订单记录</h2>
        <!-- 搜索区域 -->
        <div class="search-bar">
            <el-form :model="searchForm" label-width="auto" inline>
                <el-form-item>
                    <el-input v-model="searchForm.text" placeholder="请输入单据号/客户名/备注" clearable style="width: 222px;" />
                </el-form-item>

                <el-form-item label="有效日期：" prop="dateRange">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 392px;" @change="handleDateChange"
                        value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item label="销售员：" prop="workName" v-if="count != 6">
                    <el-input v-model="searchForm.workName" placeholder="业务员" style="width: 160px;" readonly />
                </el-form-item>

                <el-form-item label="销售员：" prop="workName" v-else>
                    <el-select v-model="searchForm.workNumber" placeholder="请选择" clearable style="width: 160px;">
                        <el-option v-for="salesPerson in salesPersonList" :key="salesPerson.id"
                            :label="salesPerson.name" :value="salesPerson.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="审核状态：">
                    <el-select v-model="searchForm.auditStatus" placeholder="(空)" clearable style="width: 140px;">
                        <el-option label="已保存" value="0" />
                        <el-option label="待审核" value="1" />
                        <el-option label="已审核" value="2" />
                        <el-option label="已驳回" value="3" />
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="仓库：">
                    <el-input v-model="input" readonly placeholder="选择仓库" @click="warehouseVisible = true"
                        style="width: 150px" />
                </el-form-item>

                <el-form-item label="商品：">
                    <el-input v-model="goodsInput" readonly placeholder="选择商品" @click="openGoodsDialog"
                        style="width: 150px" />
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>

            </el-form>
        </div>

        <!-- 操作按钮区 -->
        <div v-if="!props.selectable" class="action-bar" style="float: right; margin-bottom: 15px;">
            <el-button type="primary" @click="goToAddOrder">新增</el-button>
            <el-dropdown trigger="click">
                <el-button>审核</el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item>通过</el-dropdown-item>
                        <el-dropdown-item>驳回</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <el-dropdown trigger="click">
                <el-button>导入</el-button>
            </el-dropdown>
            <el-button @click="batchDelete" :disabled="selectedRows.length === 0">删除</el-button>
        </div>

        <div style="margin: 100px;"></div>
        <!-- 主要表格 -->
        <div class="table-container">
            <el-table :data="orderList" border stripe style="width: 100%" @selection-change="handleSelectionChange"
                @row-click="handleRowClick">
                <el-table-column type="selection" width="40" align="center" />

                <el-table-column label="操作" width="110" align="center">
                    <template #default="scope">
                        <template v-if="props.selectable">
                            <el-button size="mini" type="text" @click="selectOrder(scope.row)">选择</el-button>
                        </template>
                        <template v-else>
                            <el-button size="mini" type="text" @click="editOrder(scope.row)">编辑</el-button>
                            <el-button size="mini" type="text" @click="deleteQuote(scope.row)">删除</el-button>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="订单日期" prop="date" width="120" sortable>
                    <template #default="scope">
                        {{ formatDate(scope.row.date) }}
                    </template>
                </el-table-column>
                <el-table-column label="订单编号" prop="code" width="180" sortable />
                <!-- <el-table-column label="关联销货单号" prop="salesSlipCode" width="180" />
                <el-table-column label="关联报价单号" prop="quotationCode" width="180" /> -->

                <el-table-column label="关联销货单号" prop="salesSlipCode" width="180">
                    <template #default="scope">
                        <div v-if="scope.row.salesSlipCode">
                            <el-link v-for="code in scope.row.salesSlipCode.split(' ')" :key="code" type="primary"
                                @click="viewSalesSlip(code)" :underline="false"
                                style="display: block; margin-bottom: 2px;">
                                {{ code }}
                            </el-link>
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>

                <el-table-column label="关联报价单号" prop="quotationCode" width="180">
                    <template #default="scope">
                        <el-link v-if="scope.row.quotationCode" type="primary"
                            @click="viewQuotation(scope.row.quotationCode)" :underline="false">
                            {{ scope.row.quotationCode }}
                        </el-link>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="销售员" prop="workName" width="110" sortable />
                <el-table-column label="客户" prop="customerName" width="120" sortable />
                <el-table-column label="客户类别" prop="customerType" width="110" />
                <el-table-column label="客户地址" prop="customerAddress" width="180" show-overflow-tooltip />
                <el-table-column label="销售金额" prop="salesAmount" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.salesAmount }}
                    </template>
                </el-table-column>
                <el-table-column label="税额" prop="taxAmount" width="100" sortable>
                    <template #default="scope">
                        {{ scope.row.taxAmount }}
                    </template>
                </el-table-column>
                <!-- <el-table-column label="优惠金额" prop="taxCost" width="110" sortable>
                    <template #default="scope">
                        {{ scope.row.taxCost }}
                    </template>
                </el-table-column>
                <el-table-column label="优惠后金额" prop="taxEndCost" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.taxEndCost }}
                    </template>
                </el-table-column> -->
                <el-table-column label="数量" prop="itemCount" width="80" sortable />


                <el-table-column label="审核状态" prop="auditStatus" width="120" sortable>
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.auditStatus == '2' || scope.row.auditStatus == '0' ? 'success' : scope.row.auditStatus == '3' ? 'warning' : 'danger'"
                            size="small">
                            {{ auditStatusMap[scope.row.auditStatus] || scope.row.auditStatus }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="交货日期" prop="productDate" width="120" sortable>
                    <template #default="scope">
                        {{ formatDate(scope.row.productDate) }}
                    </template>
                </el-table-column>
                <!-- <el-table-column label="制单人" prop="makeBy" width="120" sortable /> -->
                <!-- <el-table-column label="制单时间" prop="date" width="120" sortable /> -->
                <el-table-column label="审核人" prop="checkedBy" width="120" sortable />
                <el-table-column label="备注" prop="remarks" width="120" sortable />
                <el-table-column label="交货方式" prop="delivery" width="120">
                    <template #default="scope">
                        {{ deliveryMap[scope.row.delivery] || scope.row.delivery }}
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页组件 -->
        <div style="float: right; padding-top: 20px;">
            <el-pagination background layout="prev, pager, next,jumper" :total="pageInfo.total"
                :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum" @current-change="changePage" />
        </div>

        <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="60%" style="height: auto;" draggable
            :show-close="true">
            <!-- 调用仓库的搜索组件 -->
            <WareHouse ref="warehouseRef"
                :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
            <br /><br />
        </el-dialog>

        <GoodsSelectDialog v-model:visible="goodsDialogVisible" :data-source="productDataSource"
            :selected="selectedProducts" @confirm="handleGoodsConfirm" @cancel="handleGoodsCancel" />
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, defineProps, defineEmits } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import WareHouse from '@/views/basic/WareHouse.vue'
import GoodsSelectDialog from '@/util/GoodsSelectDialog.vue'




const count = sessionStorage.getItem("count")
const staffName = sessionStorage.getItem("name")


// 控制弹窗显示
const goodsDialogVisible = ref(false)

// 商品数据源
const productDataSource = ref([
])

// 已选商品
const selectedProducts = ref([])

// // 打开商品选择弹窗
// const openGoodsDialog = () => {
//     goodsDialogVisible.value = true
// }

// 商品输入框显示值
const goodsInput = ref('')
// 确认选择商品
const handleGoodsConfirm = (selected) => {
    selectedProducts.value = selected
    // 将选中的商品名称显示在输入框中
    if (selected && selected.length > 0) {
        goodsInput.value = selected.map(item => item.name).join(',')
    } else {
        goodsInput.value = ''
    }
    goodsDialogVisible.value = false
    console.log('选中的商品:', selected)
}
// 取消选择
const handleGoodsCancel = () => {
    // 处理取消逻辑
}


let warehouseVisible = ref(false)
let input = ref('')
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
    if (!newVisible) {
        if (warehouseRef.value) {
            input.value = warehouseRef.value.selectedArray.map(item => item.name).join(',')
            warehouseRef.value.clearSelected();
        }
    }
})
const router = useRouter()

// 搜索表单
const searchForm = reactive({
    text: '',
    end_date: '',
    start_date: '',
    workName: staffName,
    auditStatus: '',
    warehouse: '',
    product: '',
    customerName: '',
    workNumber: ''
})
// 跳转新增订单
const goToAddOrder = () => {
    router.push({ name: 'salesOrder' })
}

// 分页信息
const pageInfo = reactive({
    list: [],
    total: 0,
    pageSize: 5,
    pageNum: 1,
    pages: 1,
})

// 表格数据
const orderList = ref([
])

const dateRange = ref([])
// 处理日期变化
const handleDateChange = (val) => {
    if (val && val.length === 2) {
        searchForm.start_date = val[0]
        searchForm.end_date = val[1]
    } else {
        searchForm.start_date = ''
        searchForm.end_date = ''
    }
}

// 改变页码
const changePage = (newPage) => {
    pageInfo.pageNum = newPage
    handleSearch()
}
// 选中行
const selectedRows = ref([])

// 搜索
const handleSearch = async () => {
    const params = {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,

        text: searchForm.text,
        start_date: searchForm.start_date ? searchForm.start_date : null,
        end_date: searchForm.end_date ? searchForm.end_date : null,
        workNumber: searchForm.workNumber,
        warehouse: searchForm.warehouse,
        product: searchForm.product,
        auditStatus: props.selectable ? '2' : searchForm.auditStatus
    }


    if (props.selectable && props.preFilterCustomerId) {
        params.customerId = props.preFilterCustomerId
    }

    const response = await axios.get('/api/sales/salesOrderList', { params })

    if (response.data.code == 200) {
        orderList.value = response.data.salesOrderList.list
        pageInfo.total = response.data.salesOrderList.total
        pageInfo.pageNum = response.data.salesOrderList.pageNum
        pageInfo.pageSize = response.data.salesOrderList.pageSize
        pageInfo.pages = response.data.salesOrderList.pages
    } else {
        ElMessage.error("查询失败: " + response.data.message)
    }
}
// 修改重置方法
const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
        if (typeof searchForm[key] === 'string') {
            searchForm[key] = ''
        } else if (Array.isArray(searchForm[key])) {
            searchForm[key] = []
        }
    })
    dateRange.value = []
    input.value = ''
    goodsInput.value = ''
    selectedProducts.value = []
}

// 表格事件
const handleSelectionChange = (val) => {
    selectedRows.value = val
}

const handleRowClick = (row) => {
    console.log('点击行:', row)
}

// 编辑
const editOrder = (row) => {
    router.push({
        name: 'salesOrder',
        query: {
            code: row.code,
            id: row.id,
            from: 'edit',
            status: row.auditStatus
        }
    })
}

// 删除单个
const deleteQuote = async (row) => {
    await ElMessageBox.confirm(
        `确定要删除报价单 ${row.code} 吗？。`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );

    // 发送删除请求
    const response = await axios.post('/api/sales/deleteSalesOrder', [row.id], {
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (response.data.code == 200) {
        ElMessage.success('删除成功');
        // 重新加载数据
        handleSearch();
    } else {
        ElMessage.error('删除失败: ' + response.data.message);
    }
};

// 删除
const batchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的报价单');
        return;
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 个报价单吗？`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );

    // 获取选中行的报价单编号
    const id = selectedRows.value.map(row => row.id);
    const response = await axios.post('/api/sales/deleteSalesOrder', id, {
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (response.data.code == 200) {
        ElMessage.success('删除成功');
        // 重新加载数据
        handleSearch();
    } else {
        ElMessage.error('删除失败: ' + response.data.message);
    }
};
//单据日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

const salesPersonList = ref([
])

const selectStaff = async () => {
    const response = await axios.get('/api/sales/selectStaff')
    if (response.data.code == 5200) {
        console.log('12', response.data)
        salesPersonList.value = response.data.saleStaffList
    } else {
        ElMessage.error(response.data.msg)
        console.error('获取销售员列表失败：', response.data.message)
    }
}

// 查看关联的销货单详情
const viewSalesSlip = (salesSlipCode) => {
    console.log('准备跳转到销货单详情，code:', salesSlipCode)
    if (salesSlipCode) {
        router.push({
            name: 'salesSlip',
            query: {
                code: salesSlipCode,
                from: 'view'
            }
        })
    }
}

// 查看关联的报价单详情
const viewQuotation = (quotationCode) => {
    if (quotationCode) {

        router.push({
            name: 'addQuotation',
            query: {
                code: quotationCode,
                from: 'view'
            }
        })
    }
}

// 审核状态
const auditStatusMap = {
    '0': '已保存',
    '1': '待审核',
    '2': '已审核',
    '3': '已驳回'
}

// 交货方式
const deliveryMap = {
    '1': '快递',
    '2': '自提',
    '3': '配送'
}

const props = defineProps({
    // 是否为选择模式
    selectable: {
        type: Boolean,
        default: false
    },
    // 用于源单选择
    preFilterCustomerId: {
        type: [String, Number],
        default: ''
    }
})
//重新选择客户
watch(
    () => props.preFilterCustomerId,
    (newVal, oldVal) => {
        if (props.selectable && newVal !== oldVal) {
            pageInfo.pageNum = 1
            handleSearch()
        }
    }
)
// 选择源单
const selectOrder = (row) => {
    emit('select', row)
}

const emit = defineEmits(['select'])

onMounted(() => {
    selectStaff()
    handleSearch()
})
</script>

<style scoped>
.sales-order-list-container {
    padding: 20px;
    background-color: white;
    min-height: 100vh;
}

.search-bar {
    background: white;
    padding: 15px;

    margin-bottom: 15px;

}

.action-bar {

    display: flex;
    gap: 8px;
    margin-bottom: 15px;
    flex-wrap: wrap;
    background: white;
    padding: 10px;
    border-radius: 8px;

}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    background: white;
    padding: 10px;
    border-radius: 8px;

}

.column-settings {
    display: flex;
    gap: 10px;
    align-items: center;
}

.pagination-info {
    font-size: 14px;
    color: #999;
}

.table-container {
    background: white;
    border-radius: 8px;
    margin-top: 20px;
    overflow: hidden;

}

.pagination {
    margin-top: 20px;
    text-align: right;
}

/* 响应式 */
@media (max-width: 768px) {

    .search-bar,
    .action-bar,
    .table-header {
        flex-direction: column;
        gap: 10px;
    }

    .action-bar {
        flex-wrap: wrap;
    }

    .table-container {
        overflow-x: auto;
    }
}
</style>